"""Quafu platform utilities for quantum circuit generation and execution.

This module provides functions for generating benchmark circuits and handling
quantum circuit execution on the Quafu platform.

Available quantum gates:
    - Single-qubit gates: 'rx', 'ry', 'rz', 'x', 'y', 'z', 'h'
    - Two-qubit gates: 'cx', 'cz'
    - Other operations: 'delay', 'barrier', 'measure'
"""

import json
from typing import List, Dict, Tuple, Optional, Any, Union

import numpy as np
from quafu import QuantumCircuit, Task



def submit_circ_jobs(circuit_list: List[QuantumCircuit],
                    df: Any,
                    task: Task,
                    exp_name: str,
                    compile: bool = False) -> None:
    """Submit quantum circuits to Quafu platform.

    Args:
        circuit_list: List of circuits to execute
        df: Dataframe for storing results
        task: Quafu task instance
        exp_name: Experiment name
        compile: Whether to compile circuits
    """
    for idx, circuit in enumerate(circuit_list):
        exp_id = task.send(circuit, name=exp_name, group=exp_name).taskid
        df.loc[idx, 'exp_id'] = exp_id
        df.loc[idx, 'exp_name'] = exp_name


def get_result_less_15qubits(df: Any, task: Task) -> None:
    """Get results for circuits with less than 15 qubits.

    Args:
        df: Dataframe containing experiment data
        task: Quafu task instance
    """
    if 'calibrated_exp_result' not in df.columns:
        df['calibrated_exp_result'] = None

    for row in range(len(df)):
        exp_id = df.loc[row, 'exp_id']
        result = task.retrieve(exp_id)
        if not result.probabilities:
            raise ValueError(f"No result found for experiment {exp_id}")
        df.loc[row, 'exp_result'] = json.dumps(result.probabilities)


def get_result_more_15qubits(df: Any, task: Task) -> None:
    """Get results for circuits with more than 15 qubits.

    Args:
        df: Dataframe containing experiment data
        task: Quafu task instance
    """
    if 'calibrated_exp_result' not in df.columns:
        df['calibrated_exp_result'] = None

    for row in range(len(df)):
        exp_id = df.loc[row, 'exp_id']
        result = task.retrieve(exp_id)
        if not result.probabilities:
            raise ValueError(f"No result found for experiment {exp_id}")
        df.loc[row, 'exp_result'] = json.dumps(result.probabilities)